package com.hyzx.qbasic.admin.domain.integration;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.hyzx.qbasic.admin.common.config.AliyunConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;
import java.util.List;

/**
 * Created by 黄江华 on 2018/10/8.
 */

@Component
public class AliyunOssClient {
    private static final Logger logger = LoggerFactory.getLogger(AliyunOssClient.class);

    @Autowired
    private AliyunConfig aliyunConfig;

    @Autowired
    private OSSClient ossClient;

    public boolean uploadFile(File file, String filePath) {
        try {
            ossClient.putObject(aliyunConfig.getOssBucketName(), filePath, file);
            return true;
        } catch (Exception ex) {
            logger.error("OSS服务上传文件异常", ex);
        }

        return false;
    }

    public boolean uploadFile(InputStream inputStream, String filePath) {
        try {
            ossClient.putObject(aliyunConfig.getOssBucketName(), filePath, inputStream);
            return true;
        } catch (Exception ex) {
            logger.error("OSS服务上传文件异常", ex);
        }

        return false;
    }

    public boolean deleteFile(String fileName) {
        try {
            // 检查文件是否存在
            boolean objectExist = ossClient.doesObjectExist(aliyunConfig.getOssBucketName(), fileName);
            if (objectExist) {
                ossClient.deleteObject(aliyunConfig.getOssBucketName(), fileName);
            }

            return true;
        } catch (Exception ex) {
            logger.error("OSS服务删除文件异常", ex);
        }

        return false;
    }

    public boolean batchDeleteFile(List<String> fileNames) {
        try {
            ossClient.deleteObjects(
                    new DeleteObjectsRequest(aliyunConfig.getOssBucketName()).withKeys(fileNames));
            return true;
        } catch (Exception ex) {
            logger.error("OSS服务批量删除文件异常", ex);
        }

        return false;
    }
}
